package xyz.gzdxc.common.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.gzdxc.common.mysql.entity.MenuEntity;
import xyz.gzdxc.common.mysql.repository.MenuRepository;
import xyz.gzdxc.common.service.MenuService;
import xyz.gzdxc.common.vo.response.MenuTreeVo;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    private static final Logger LOG = LoggerFactory.getLogger(MenuServiceImpl.class);

    @Autowired
    MenuRepository menuRepository;

    @Override
    public List<MenuEntity> getMenuListByUserId(Long userId) {
        return menuRepository.getMenuListByUserId(userId);
    }

    @Override
    public List<MenuTreeVo> getMenuTreeByUserId(Long userId) {
        LOG.info("userId => {}", userId);
        List<MenuEntity> menuEntityList = menuRepository.getMenuListByUserId(userId);
        LOG.info("menuEntityList => {}", menuEntityList);
        List<MenuTreeVo> menuTreeVoList = new ArrayList<>();
        MenuTreeVo menuTreeVo = null;
        if(menuEntityList != null && menuEntityList.size() > 0){
            for(MenuEntity menuEntity : menuEntityList){
                if(menuEntity.getParMenuCode() == null){
                    menuTreeVo = new MenuTreeVo();
                    menuTreeVo.setTitle(menuEntity.getMenuName());
                    menuTreeVo.setMenuCode(menuEntity.getMenuCode());
                    menuTreeVo.setPath(menuEntity.getPath());
                    menuTreeVo.setName(menuEntity.getName());
                    menuTreeVoList.add(menuTreeVo);
                }
            }
            LOG.info("menuTreeVoList => {}", menuTreeVoList);
            if(menuTreeVoList.size() > 0){
                translateMenuTree(menuTreeVoList, menuEntityList);
                return menuTreeVoList;
            }
        }
        return null;
    }

    private void translateMenuTree(List<MenuTreeVo> treeVoList, List<MenuEntity> menuEntityList){
        if(treeVoList.size() < 1 || menuEntityList.size() < 1){
            return;
        }
        MenuTreeVo childrenMenuTreeVo;
        for(MenuTreeVo menuTreeVo : treeVoList){
            for(MenuEntity menuEntity : menuEntityList){
                if(menuTreeVo.getMenuCode().equals(menuEntity.getParMenuCode())){
                    childrenMenuTreeVo = new MenuTreeVo();
                    childrenMenuTreeVo.setTitle(menuEntity.getMenuName());
                    childrenMenuTreeVo.setMenuCode(menuEntity.getMenuCode());
                    childrenMenuTreeVo.setPath(menuEntity.getPath());
                    childrenMenuTreeVo.setName(menuEntity.getName());
                    menuTreeVo.getChildren().add(childrenMenuTreeVo);
                }
            }
            translateMenuTree(menuTreeVo.getChildren(), menuEntityList);
        }
    }
}
